package com.liuer.controller;

import com.liuer.dto.UserDTO;
import com.liuer.entity.User;
import com.liuer.service.LoginService;
import com.liuer.util.JwtUtils;
import com.liuer.util.Result;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping()
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 登录请求验证
     * @return
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody UserDTO userDTO){


        // 暂时屏蔽验证码相关操作
        // 获取Redis操作对象
        ValueOperations valueOperations = redisTemplate.opsForValue();

        // // 遍历cookies 从Cookies中获取 CaptchaKey
        // String captchaKey = null;
        // Cookie[] cookies= request.getCookies();
        // if (cookies != null) {
        //     for (Cookie cookie : cookies) {
        //         if ("CaptchaKey".equals(cookie.getName())) {
        //             captchaKey = cookie.getValue();
        //             break;
        //         }
        //     }
        // }
        //
        // // 如果未找到 CaptchaKey，返回错误
        // if (captchaKey == null) {
        //     return Result.error("验证码已过期，请刷新重试");
        // }
        //
        // // 从 Redis 中获取验证码
        // String verCodeInRedis = (String) valueOperations.get(captchaKey);
        // if (verCodeInRedis == null) {
        //     return Result.error("验证码已过期，请刷新重试");
        // }
        //
        // // 验证用户输入的验证码是否正确
        // if (!verCodeInRedis.equalsIgnoreCase(userDTO.getVerCode())) {
        //     return Result.error("验证码错误");
        // }

        User user = loginService.login(userDTO);

        // 首先根据用户名判断用户是否存在
        if(loginService.getUserByUsername(userDTO.getUsername()) == null) {
            log.info("User not exist!");
            return Result.error("The username does not exist");
        }


        if(user != null){
            log.info("验证成功！！！");
            // 生成JWT令牌
            Map<String,Object> claims = new HashMap<>();
            claims.put("userId",user.getId());
            String jwt = JwtUtils.generateJwt(claims);
            return Result.success(jwt);
        }
        else
            return Result.error("Username or Password Error!!!");
    }
}
